﻿using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Interactivity;
using LiveHub.DataModels;

namespace LiveHub.AvaloniaApp.Dialogs;

public partial class GroupDialog : UserControl
{
    private readonly string jwt;

    public GroupDialog(bool isCreate, string _jwt)
    {
        jwt = _jwt;
        InitializeComponent();
        CreateGroupPanel = this.FindControl<StackPanel>("CreateGroupPanel");
        if (CreateGroupPanel != null) CreateGroupPanel.IsVisible = isCreate;
        JoinGroupPanel = this.FindControl<StackPanel>("JoinGroupPanel");
        if (JoinGroupPanel != null) JoinGroupPanel.IsVisible = !isCreate;
    }

    public GroupModel? CreateGroup()
    {
        if (string.IsNullOrEmpty(NameBox.Text)) return null;
        return new GroupModel
        {
            Name = NameBox.Text
        };
    }

    private async void SearchClick(object? sender, RoutedEventArgs e)
    {
        await Search();
    }

    private async Task Search()
    {
        if (string.IsNullOrEmpty(SearchBox.Text)) return;
        var http = new UserHttp()
        {
            Jwt = jwt
        };
        var result = await http.GetGroupFromId(SearchBox.Text);
        if (result == null) return;
        GroupList.ItemsSource = new[] { result };
    }

    public GroupModel? JoinGroup() => GroupList.SelectedItem as GroupModel;
}